package com.start.common.dic;

import com.start.common.entity.StartDicData;
import com.start.common.entity.StartDicGroup;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

public class DicApiManage {
    private static final DicApiManage dicApiManage = new DicApiManage();
    private Vector<StartDicData> dicApi = new Vector<>();
    private LinkedHashMap<String, List<StartDicData>> groupMap = new LinkedHashMap<>();
    private static final String DEFAULT_DIC_GROUP = "默认分组";

    public static DicApiManage getInstance() {
        return dicApiManage;
    }

    private DicApiManage() {

    }
    public void addApi(DicApi api, String url) {
        StartDicData dicData = new StartDicData();
        dicData.setLabel(api.value());
        dicData.setValue(url);
        if (StringUtils.isEmpty(dicData.getLabel())) {
            dicData.setLabel(url);
        }
        addApi(dicData, api.group());
    }

    public void addApi(StartDicData data) {
        addApi(data, null);
    }

    public void addApi(StartDicData data, String group) {
        long count = dicApi.stream().filter(e -> e.getValue().equals(data.getValue())).count();
        if (count > 0) {
            throw new RuntimeException("已存在相同访问地址dicApi");
        }
        dicApi.add(data);
        if (StringUtils.isEmpty(group)) {
            group = DEFAULT_DIC_GROUP;
        }
        List<StartDicData> groups;
        if (groupMap.containsKey(group)) {
            groups = this.groupMap.get(group);
        } else {
            groups = new ArrayList<>();
        }
        groups.add(data);
    }

    public List<StartDicGroup> getAllDicApis(String searchLabel) {
        Set<Map.Entry<String, List<StartDicData>>> entries = groupMap.entrySet();
        List<StartDicGroup> result = new ArrayList<>();
        for (Map.Entry<String, List<StartDicData>> entry : entries) {
            if(StringUtils.isEmpty(searchLabel)){
                result.add(new StartDicGroup(entry.getKey(), entry.getValue()));
            }else{
                List<StartDicData> startDicData = entry.getValue().stream().filter(e -> e.getLabel().contains(searchLabel)).collect(Collectors.toList());
                if(!startDicData.isEmpty()){
                    result.add(new StartDicGroup(entry.getKey(), startDicData));
                }
            }

        }
        return result;

    }

}
